<?php
session_start();
if ( !defined('ABSPATH') ) define( 'ABSPATH', dirname(__FILE__) . '/' );
include_once('saet.ex.class.php');
include_once('config/config.php');
include_once('include/dao/UserDAO.php');
include_once('include/control/common.php.inc');

if($_GET["s"]=="go"){
	$oauth = new SaeTOAuth(WB_AKEY,WB_SKEY);
	$request_token = $oauth->getRequestToken();
	$request_token["HTTP_REFERER"] = $_GET["url"] ? $_GET["url"]: getenv("HTTP_REFERER"); //add ref url
	
	$_SESSION['oauth_request_token'] = $request_token;

	$callback_url='http://' . $_SERVER['HTTP_APPNAME'] . '.sinaapp.com/oauth.php?s=back';
	$aurl = $oauth->getAuthorizeURL($request_token['oauth_token'],true,$callback_url);
	$aurl = $aurl."&source=".WB_AKEY;
	header("Location: $aurl");

}elseif($_GET["s"]=="back"){
	if(!isset($_SESSION['oauth_request_token'])){
		echo " <a href=\"/\">time out, go home!</a>";
		return;
	}
	$request_token = $_SESSION['oauth_request_token'];

	$oauth = new SaeTOAuth(WB_AKEY,WB_SKEY,
	$request_token['oauth_token'],
	$request_token['oauth_token_secret']);

	$access_token = $oauth->getAccessToken($_REQUEST['oauth_verifier']);
	$_SESSION['oauth_access_key'] = $access_token;

	$tclient = new SaeTClient(WB_AKEY,WB_SKEY,
	$access_token['oauth_token'],
	$access_token['oauth_token_secret']);

	//account/verify_credentials
	$user  = $tclient->verify_credentials();
	if($user === false || $user === null){
		echo "Error occured";
		return false;
	}

	if (isset($user['error_code']) && isset($user['error'])){
		echo ('Error_code: '.$user['error_code'].';  Error: '.$user['error'] );
		return false;
	}

	$usr = store_user($user,$access_token);
	set_current_user($usr);
	
	//redirect to referer url
	header("Location: " . $request_token["HTTP_REFERER"]);

}else{
	echo "<a href=\"/\">返回首页</a>";
}

function store_user($user,$access_token){
	$usr= new UserDetails();
	$usr-> id = intval($user['id']);
	$usr-> name = strip_tags($user['name']);
	$usr-> screen_name = strip_tags($user['screen_name']);
	$usr-> profile_image_url = strip_tags($user['profile_image_url']);
	$usr-> profile = strip_tags($user['description']);
	$usr-> access_token = $access_token['oauth_token'];
	$usr-> access_token_secret = $access_token['oauth_token_secret'];
	
	$userdao = new UserDAO();
	$userdao -> save($usr);
	return $usr;
}

?>